<?php
// +----------------------------------------------------------------------
// | KITEGO-Admin「开箱即用」「人人全栈」
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2024 https://www.kitego.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed KITEGO并不是自由软件，未经许可不能去掉KITEGO相关版权
// +----------------------------------------------------------------------
// | Author: KITEGO Team <bd@kitego.cn>
// +----------------------------------------------------------------------

namespace app\adminapi\services\setting;

use app\dao\setting\AttachmentDao;
use kitego\base\BaseService;
use kitego\enum\AttachmentEnum;
use kitego\enum\StorageEnum;
use kitego\extend\storage\StorageProvider;

class AttachmentService extends BaseService
{
    public function __construct(AttachmentDao $dao)
    {
        $this->dao = $dao;
    }

    /**
     * 附件列表
     */
    public function attachmentList($params)
    {
        $where[] = ['type', '=', $params['type']];
        $where[] = ['is_delete', '=', 0];

        if (!empty($params['name'])) $where[] = ['name', 'like', '%' . $params['name'] . '%'];
        if (isset($params['cid']) && is_numeric($params['cid'])) $where[] = ['cid', '=', $params['cid']];
        if (!empty($params['source'])) $where[] = ['source', '=', $params['source']];

        $attachmentList = $this->dao->page($where);
        foreach ($attachmentList['data'] as &$v) {
            $domain = $v['storage_type'] == StorageEnum::LOCAL ? request()->domain() : $v['domain'];
            $v['url'] = $domain . '/' . $v['url'];
        }

        return success($attachmentList);
    }

    /**
     * 附件移动
     */
    public function attachmentMove($ids, $cid)
    {
        return success($this->dao->update([['id', 'in', $ids]], ['cid' => $cid]));
    }

    /**
     * 附件重命名
     */
    public function attachmentRename($id, $name, $type)
    {
        // 命名是否重复
        $existQuery = $this->dao->find([['type', '=', $type], ['name', '=', $name]]);
        if ($existQuery) exception('文件名称已存在');

        return success($this->dao->update($id, ['name' => $name]));
    }

    /**
     * 附件删除
     */
    public function attachmentDelete($ids)
    {
        // 远程删除 // 数据库删除
        $urls = $this->dao->getColumn([['id', 'in', $ids]], ['url', 'storage_id'], 'id');
        foreach ($urls as $id => $v) {
            $storageProvider = app()->make(StorageProvider::class, [$v['storage_id']])->getStrategy();
            $res = $storageProvider->delete($v['url']);

            if (!$res) continue;

            $this->dao->update($id, ['is_delete' => 1]);
        }


        return success();
    }

    /**
     * 附件上传
     * @param string|null $cid 分类id
     * @param string $uploadType 文件类型 image|video|file
     * @param int|null $uploadSource 上传来源 [1-后台 2-用户]
     */
    public function attachmentUpload(string|null $cid, string $uploadType, int|null $uploadSource = AttachmentEnum::FILE_UPLOAD_SOURCE_ADMIN)
    {
        $storageProvider = app()->make(StorageProvider::class)->getStrategy();
        $storageProvider->setUploadFile('file', $uploadType);
        $fileInfo = $storageProvider->getFileInfo();
        $fileUploadDir = $storageProvider->setUploadDir();
        $fileName = $storageProvider->getFileName();

        // 上传文件
        if (!$storageProvider->upload($fileUploadDir)) exception($storageProvider->getError());

        // 入库
        $data = $this->dao->save([
            'cid' => empty($cid) ? 0 : $cid,
            'storage_id' => $fileInfo['storage_id'],
            'storage_type' => $fileInfo['storage_type'],
            'uploader_user_id' => request()->userId,
            'type' => AttachmentEnum::getFileUploadType($uploadType),
            'name' => $fileInfo['name'],
            'url' => $fileUploadDir . '/' . str_replace("\\", "/", $fileName),
            'domain' => $fileInfo['domain'],
            'source' => $uploadSource,
        ]);

        return success($data);
    }
}